<template>
  <div
    :id="id"
    :style="{
      width: width,
      height: height
    }"
    v-echart-resize
  ></div>
</template>

<script setup>
import { defineProps, onMounted, onUnmounted, ref, watch } from 'vue'
import * as echarts from 'echarts'
import { unwarp } from '@/utils/commUtils'

const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  value: {
    type: Object,
    default: () => {}
  }
})
const chart = ref(null)
const setOptions = (item) => {
  if (item === undefined) return
  const data = []
  for (let index in item) {
    data.push({
      value: item[index].rate,
      name: item[index].manufacturer
    })
  }
  const option = {
    height: '100%',
    tooltip: {
      trigger: 'item',
      formatter: '{b} : {c}%'
    },
    legend: {
      orient: 'vertical',
      top: 'center',
      icon: 'circle',
      right: 127,
      itemWidth: 17,
      itemHeight: 20,
      itemGap: 15,
      textStyle: {
        color: '#666',
        fontSize: 16
      }, // 图例文字颜色
      formatter: (parmse) => {
        return ' ' + ' ' + parmse
      }
    },
    title: {
      x: 'center',
      y: '43%'
    },
    series: [
      {
        type: 'pie',
        radius: ['60%', '70%'],
        center: ['40%', '55%'],
        color: ['#029BFD', '#067BCC', '#3FCE6A', '#00BFC6'],
        itemStyle: {
          normal: {
            borderWidth: 5,
            borderColor: '#ffffff'
          }
        },
        data,
        labelLine: {
          normal: {
            show: true,
            length: 50,
            length2: 50
          }
        },
        label: {
          normal: {
            textStyle: {
              color: 'inherit', // 提示文字颜色
              fontSize: 15 // 提示文字大小
            },
            formatter: '{c}%\n',
            padding: [0, -40]
          }
        }
      }
    ]
  }
  unwarp(chart.value).setOption(option)
}

const initChart = () => {
  setTimeout(() => {
    if (!chart.value) {
      chart.value = echarts.init(document.getElementById(props.id))
    }
    setOptions()
  }, 0)
}

onMounted(() => {
  initChart()
})

onUnmounted(() => {
  if (!chart.value) {
    return
  }
  chart.value.dispose()
  chart.value = null
})
watch(
  () => props.value,
  () => {
    setOptions(props.value)
  }
)
</script>

<style lang="scss" scoped>
</style>
